import {Component, OnInit, ViewEncapsulation, ViewChild} from '@angular/core';
import {TrainService} from "app/pages/train/train.service";
import {ActivatedRoute, Params, Router} from "@angular/router";
import {SeedInfiniteScroll} from "app/shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {CalendarBtnConfig} from "../../../../interface";
import {ToolsService} from "@shared/service/tools/tools.service";
import {AuthService} from "@shared/service/auth/auth.service";

@Component({
  selector: 'class-list',
  templateUrl: './class-list.component.html',
  styleUrls: ['./class-list.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ClassListComponent implements OnInit {
  public classes = [];
  public btnConfig: CalendarBtnConfig = new CalendarBtnConfig();
  public stateStore = {
    showDateFilter: true,
    haveData: true
  };
  public dataStore = {
    identityType: '',
    pageTitle: '',
    pageType: '',
    rightContentType: ''
  };
  public params = {
    studentId: null, // 家长端需要该参数
    beginTime: '',
    endTime: '',
    page: 1,
    rows: 10,
    orgUserId: ''
  };
  @ViewChild(SeedInfiniteScroll) infiniteScroll;

  constructor(private  trainService: TrainService,
              private router: Router,
              private route: ActivatedRoute,
              private tools: ToolsService,
              private _authService: AuthService) {
    this.setCanlenderBtn();
    this.route.params
      .switchMap((params: Params) => {
        this.handlePageTitle(params['identityType']);
        return this.route.queryParams;
      }).subscribe((queryParams: Params) => {
      this.params.studentId = queryParams['studentId'];
      this.params.orgUserId = queryParams['authOrgId'];
      this._authService.setAuthOrgId(queryParams['authOrgId']);
    });
  }

  setCanlenderBtn() {
    const btnConfig = this.btnConfig;
    btnConfig.week = true;
    btnConfig.month = true;
    btnConfig.year = true;
  }

  /**
   * @description 根据传参类型更改页面标题
   * @author ouyqx-691
   * @date 2018-1-2
   */
  handlePageTitle(identityType: string) {
    const dataStore = this.dataStore;
    dataStore.identityType = identityType;
    if (identityType === 'teacher') {
      dataStore.pageTitle = '课后点评';
      dataStore.rightContentType = 'time';
    }
    if (identityType === 'parent') {
      dataStore.pageTitle = '课后点评';
      dataStore.rightContentType = 'state';
    }

    const url = location.pathname;
    if (url.includes('/train/plan/teacher/classes')) {// 教案
      this.dataStore = {
        pageTitle: '选择班级',
        pageType: 'plan',
        rightContentType: 'state',
        identityType: 'teacher'
      };
    }
  }

  /**
   * 获取时间之后去请求
   * @param val
   */
  getCalendarTime(val) {
    let beginTime;
    let endTime;
    this.classes = [];
    const params = this.params;
    params.page = 1;
    this.infiniteScroll.enable(true);
    if (this.dataStore.identityType === 'parent') {
      beginTime = val[0].getTime();
      endTime = val[1] ? val[1].getTime() : new Date(this.tools.dateTostr(val[0]) + ' 23:59').getTime();
    } else {
      beginTime = this.tools.dateTostr(val[0]);
      endTime = val[1] ? this.tools.dateTostr(val[1]) : beginTime;
    }
    params.beginTime = beginTime;
    params.endTime = endTime;
    this.getClassListForIdentityType();
  }

  /**
   * @description 根据身份请求相应方法
   * @author ouyqx-691
   * @date 2017-1-5
   */
  getClassListForIdentityType() {
    if (this.dataStore.identityType === 'parent') {
      this.getClassListForParent();
    } else {
      this.getClassListForTeacher();
    }
  }

  /**
   * @description 班级列表（家长）
   * @author ouyqx-691
   * @date 2017-12-30
   */
  getClassListForParent(): void {
    const params = JSON.parse(JSON.stringify(this.params).replace(/Time/g, "TimeStamp")); // 更改参数名
    this.trainService.getClassListForParent(params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.params.page++;
        const classes = res.data.list;
        this.infiniteScroll.complete();
        this.classes = [...this.classes, ...classes];
        if (!res.data.hasNextPage) {
          this.infiniteScroll.enable(false);
        }
        if (classes.length === 0) {
          return this.stateStore.haveData = false;
        } else {
          return this.stateStore.haveData = true;
        }
      } else {
        return this.stateStore.haveData = false;
      }
    });
  }

  /**
   * @description 班级列表（教练）
   * @author ouyqx-691
   * @date 2017-12-30
   */
  getClassListForTeacher(): void {
    this.trainService.getClassListForTeacher(this.params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        const classes = res.data.list;
        this.params.page++;
        this.infiniteScroll.complete();
        this.classes = [...this.classes, ...classes];
        if (!res.data.hasNextPage) {
          this.infiniteScroll.enable(false);
        }
        if (classes.length === 0) {
          return this.stateStore.haveData = false;
        } else {
          return this.stateStore.haveData = true;
        }
      } else {
        return this.stateStore.haveData = false;
      }
    });
  }

  /**
   * @description 前往目标页
   * @author ouyqx-691
   * @date 2017-12-31
   */
  goToTarget(classItem): void {
    const type = this.dataStore.pageType;
    const identityType = this.dataStore.identityType;
    const {classScheduleId, name, classId, scheduleName} = classItem;
    if (type === 'plan') {// 点评教案
      const navigationExtras = {
        queryParams: {'className': scheduleName, classId: classId},
      };
      this.router.navigate([`/train/plan/class`, classId], navigationExtras);
      return;
    }

    if (identityType === 'parent') {// 点评家长
      this.router.navigate([`/train/remark/parent/lessons`], {
        queryParams: {
          classId: classItem.classId,
          studentId: this.params.studentId,
          teacherId: classItem.teacherId
        }
      });
      return;
    }
    if (identityType === 'teacher') {  // 教练端
      this.router.navigate([`/train/remark/teacher/students`], {
        queryParams: {
          classId: classScheduleId,
          teacherId: classItem.teacherId,
          beginTime: this.params.beginTime,
          endTime: this.params.endTime
        }
      });
      return;
    }
  }

  ngOnInit() {
  }
}
